﻿using System;

/* 【选做】写一个int类型的单向LinkedList，有Add、Count、get、isEmpty，delete(下标)，insert */
namespace Practice15
{
    public class LinkedList
    {
        private Node head;
        private int size;

        private class Node
        {
            public int Data;
            public Node Next;

            public Node(int data)
            {
                Data = data;
                Next = null;
            }
        }

        public LinkedList()
        {
            head = null;
            size = 0;
        }

        public void Add(int data)
        {
            Node newNode = new Node(data);

            if (head == null)
            {
                head = newNode;
            }
            else
            {
                Node current = head;
                while (current.Next != null)
                {
                    current = current.Next;
                }
                current.Next = newNode;
            }
            size++;
        }

        public void Insert(int index, int data)
        {
            if (index < 0 || index > size)
            {
                throw new IndexOutOfRangeException("超出范围");
            }
            Node newNode = new Node(data);
            if (index == 0)
            {
                newNode.Next = head;
                head = newNode;
            }
            else
            {
                Node current = head;
                for (int i = 0; i < index - 1; i++)
                {
                    current = current.Next;
                }
                newNode.Next = current.Next;
                current.Next = newNode;
            }
            size++;
        }

        public int Get(int index)
        {
            if (index < 0 || index > size)
            {
                throw new IndexOutOfRangeException("超出范围");
            }
            Node current = head;
            for (int i = 0; i < index; i++)
            {
                current = current.Next;
            }
            return current.Data;
        }

        public void Delete(int index)
        {
            if (index < 0 || index > size)
            {
                throw new IndexOutOfRangeException("超出范围");
            }
            Node current = head;
            for (int i = 0; i < index - 1; i++)
            {
                current = current.Next;
            }
            current.Next = current.Next.Next;
            size--;
        }

        public int Count
        {
            get{ return size; }
        }

        public bool IsEmpty
        {
            get { return size == 0; }
        }
    }
}